/*******************************************
 * Copyright 2007 Aphrodite Framework for javaME .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Email : owner@aphroditeme.dev.java.net
 * Contributors:
 *     Kent Elton - initial API and implementation
 *******************************************/

package com.aphrodite.extns.bluetooth;

import java.io.IOException;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;

/**
 * Represents a bluetooth device
 * 
 * @author kentelt
 * 
 */
public final class Device implements DiscoveryListener {

	public String address;

	public String name;

	private RemoteDevice remoteDevice;

	private boolean searchComplete;

	private Service[] services;

	protected Device(RemoteDevice remotedevice) {
		remoteDevice = remotedevice;
		address = remotedevice.getBluetoothAddress();
		name();
	}

	public String address() {
		return remoteDevice.getBluetoothAddress();
	}

	public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {

	}

	public void findServices() {

		searchComplete = false;
		UUID allServices = new UUID(256L);
		UUID[] uuidSet = new UUID[] { allServices };
		int[] attrSet = new int[] { 0x0100, 0x0003, 0x0004 };

		// Get the discovery agent
		LocalDevice localDevice = null;
		try {
			localDevice = LocalDevice.getLocalDevice();

			DiscoveryAgent discoveryAgent = localDevice.getDiscoveryAgent();
			discoveryAgent.searchServices(attrSet, uuidSet, remoteDevice, this);

		} catch (BluetoothStateException e) {
			e.printStackTrace();
		}

	}

	protected RemoteDevice getRemoteDevice() {
		return remoteDevice;
	}

	public Service[] getServices() {
		return services;
	}

	public void inquiryCompleted(int discType) {

	}

	public String name() {
		if (name == null)
			try {
				name = remoteDevice.getFriendlyName(false);
				return name;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
		return "Unknown";
	}

	public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
		services = new Service[servRecord.length];
		for (int i = 0; i < servRecord.length; i++) {
			services[i] = new Service(this, servRecord[i]);
		}
	}

	public boolean serviceSearchComplete() {
		return searchComplete;
	}

	public void serviceSearchCompleted(int transID, int respCode) {
		searchComplete = true;
	}

	public String toString() {
		return name();
	}
}
